package com.blb.day13_demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blb.day13_demo.entity.Account;
import com.blb.day13_demo.mapper.AccountMapper;
import com.blb.day13_demo.service.AccountService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

/**
 * 账户业务实现
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {

    @Transactional
    @Override
    public void transfer(int outId, int toId, float money) {
        //查询转出账户，余额是否足够
        Account out = getById(outId);
        if(out.getBalance() < money){
            throw new RuntimeException("余额不足");
        }
        //查询转入账户
        Account to = getById(toId);
        //修改余额,转出
        out.setBalance(out.getBalance() - money);
        updateById(out);
        //模拟异常
        if(new Random().nextInt(2) == 0) {
            throw new RuntimeException("error!");
        }
        //修改余额,转入
        to.setBalance(to.getBalance() + money);
        updateById(to);
    }
}
